(function() {
  'use strict';

  angular.module('DeployTool.tasktrack', [])
    .config(['$stateProvider', TaskTrackConfig])
    .controller('TaskTrackListController', ['TaskTrackService', '$filter', '$rootScope', TaskTrackListController])
    .controller('TaskTrackPanelController', ['$stateParams', '$interval', '$timeout', 'TaskTrackService', TaskTrackPanelController])
    .controller('TaskTrackInfoController', ['$stateParams', '$rootScope', '$scope', '$interval', 'TaskTrackService', TaskTrackInfoController]);

  function TaskTrackConfig($stateProvider) {
    $stateProvider
      .state('menu.tasktrack', {
        url: '/tasktrack',
        views: {
          'main': {
            template: '<div ui-view="tasktrack" class="task-track"></div>',
          }
        }
      })
      .state('menu.tasktrack.list', {
        url: '/list',
        views: {
          'tasktrack': {
            templateUrl: 'modules/tasktrack/tasktrack.list.html',
            controller: 'TaskTrackListController',
            controllerAs: 'vm'
          }
        }
      })
      .state('menu.tasktrack.panel', {
        url: '/panel/:taskId',
        views: {
          'tasktrack': {
            templateUrl: 'modules/tasktrack/tasktrack.panel.html',
            controller: 'TaskTrackPanelController',
            controllerAs: 'vm'
          }
        }
      })
      .state('menu.tasktrack.info', {
        url: '/info/:taskId',
        views: {
          'tasktrack': {
            templateUrl: 'modules/tasktrack/tasktrack.info.html',
            controller: 'TaskTrackInfoController',
            controllerAs: 'vm'
          }
        }
      });
  }

  function TaskTrackListController(TaskTrackService, $filter, $rootScope) {
    var vm = this;

    vm.taskPlanList = null;
    vm.keyWord = '';
    vm.projectValid = {
      projectName: '',
      executor: '',
      file: '',
    };

    vm.currentProject = {
      projectId: '',
      projectName: '',
      executor: '',
      description: '',
      dateText: '',
      projectFileName: '',
      fileStatus: '',
    };

    vm.projectFile = {
      name: '',
      file: ''
    };

    vm.searchProject = searchProject;
    vm.saveProject = saveProject;
    vm.delProject = delProject;

    vm.downloadProFile = downloadProFile;

    vm.showModal = showModal;
    vm.colseModal = colseModal;

    vm.projectStatus = TaskTrackService.getProjectStatus();

    vm.paginationOpt = {
      currentPage: 1,
      itemsPerPage: 10,
      totalItems: 0,
      onChange: getTaskPlanList
    };

    activate();

    //////////////////////////////////////

    function activate() {
      getTaskPlanList(1);
    }

    function searchProject(event) {
      var keyCode;
      if (event) {
        keyCode = window.event ? event.keyCode : event.which;
        if (keyCode === 13) {
          getTaskPlanList(1);
        }
      } else {
        getTaskPlanList(1);
      }
    }

    function getTaskPlanList(page) {
      vm.paginationOpt.currentPage = page;
      var data = {
        page: vm.paginationOpt.currentPage,
        size: 10,
        keyWord: vm.keyWord
      };
      TaskTrackService.getTaskPlanList(data).then(function(taskPlanList) {
        vm.taskPlanList = taskPlanList;
        vm.paginationOpt.totalItems = taskPlanList.total || 0;
      }, function(msg) {
        throw msg;
      });
    }

    function saveProject() {
      if (!validCurrentProject(vm.projectValid)) {
        return;
      }
      var formData = new FormData();
      if (vm.projectFile.file) {
        formData.append('excelFile', vm.projectFile.file);
      }
      formData.append('projectName', vm.currentProject.projectName);
      formData.append('executor', vm.currentProject.executor);
      formData.append('description', vm.currentProject.description);
      formData.append('dateText', vm.currentProject.dateText);

      if (!vm.currentProject.projectId) {
        saveNewProject(formData);
      } else {
        formData.append('projectId', vm.currentProject.projectId);
        updateProject(formData);
      }
    }

    function saveNewProject(formData) {
      TaskTrackService.addProject(formData).then(function(projectId) {
        getTaskPlanList(1);
        $rootScope.showMessage('新增项目成功', 'success', 3);
        colseModal();
      }, function(msg) {
        $rootScope.showMessage(msg, 'danger');
        colseModal();
      });
    }

    function updateProject(formData) {
      TaskTrackService.updateProject(formData).then(function(projectId) {
        getTaskPlanList(vm.paginationOpt.currentPage);
        $rootScope.showMessage('更新项目成功', 'success', 3);
        colseModal();
      }, function(msg) {
        $rootScope.showMessage(msg, 'danger');
        colseModal();
      });
    }

    function showModal(project) {
      angular.element('#addPorject').modal();
      angular.element('#dateText').datepicker({
        dateFormat: 'yy-mm-dd'
      });
      if (!project.projectId) {
        project.dateText = $filter('date')(new Date(), 'yyyy-MM-dd');
      } else {
        vm.projectFile.name = project.projectFileName;
        vm.currentProject = _.clone(project);
      }
    }

    function colseModal() {
      vm.currentProject = {};
      vm.projectFile.file = '';
      vm.projectFile.name = '';
      vm.projectValid = {};
      angular.element('#addPorject').modal('hide');
    }

    function validCurrentProject(valid) {
      if (!vm.currentProject.projectName) {
        valid.projectName = 'empty';
      } else if (vm.currentProject.projectName.length > 100) {
        valid.projectName = 'long';
      }
      if (!vm.currentProject.executor) {
        valid.executor = 'empty';
      } else if (vm.currentProject.executor.length > 100) {
        valid.executor = 'long';
      }
      if (!vm.projectFile.name) {
        valid.file = 'empty';
      } else {
        var name = vm.projectFile.name.split('.');
        if (name[name.length - 1] !== 'xls') {
          valid.file = 'innegal';
        }
      }
      return !valid.projectName && !valid.executor && !valid.file;
    }

    function downloadProFile(projectId) {
      var fileUrl = TaskTrackService.downloadFile(projectId);
      document.getElementById('downloadFile').href = fileUrl;
      document.getElementById('downloadFile').click();
    }

    function delProject(projectId) {
      TaskTrackService.delTaskPlan(projectId).then(function() {
        getTaskPlanList(1);
        $rootScope.showMessage('操作成功', 'success', 3);
      }, function(msg) {
        $rootScope.showMessage(msg, 'danger');
      });
    }
  }

  function TaskTrackPanelController($stateParams, $interval, $timeout, TaskTrackService) {
    var vm = this;

    var intervalTime = 60;
    var mincell = 6;
    var minpixel = 22;

    vm.currentTime = {};
    vm.taskPlanInfo = {};
    vm.currentTask = {};

    vm.showTaskDetailsModal = showTaskDetailsModal;

    activate();

    //////////////////////////////////////

    function activate() {
      if ($stateParams.taskId) {
        getTaskPlanInfo($stateParams.taskId);
      }
      respondPageRender();
    }

    function respondPageRender() {
      angular.element('.task-track-panel .task-panel').css({ 'height': angular.element(window).height() - 130 + 'px' });
      angular.element(window).resize(function() {
        angular.element('.task-track-panel .task-panel').css({ 'height': angular.element(window).height() - 130 + 'px' });
      });

      angular.element('.task-track-panel .task-panel').scroll(function(event) {
        var offsetLeft = angular.element('.task-track-panel .task-panel').scrollLeft();
        var offsetTop = angular.element('.task-track-panel .task-panel').scrollTop();

        angular.element('.task-track-panel .task-panel .task-panel-head .task-panel-th').css({ 'top': offsetTop + 'px' });
        angular.element('.task-track-panel .task-panel .task-panel-head .task-panel-th').css({ 'left': offsetLeft + 'px' });
        angular.element('.task-track-panel .task-panel .task-panel-head .task-panel-time').css({ 'top': offsetTop + 'px' });
        angular.element('.task-track-panel .task-panel .task-panel-body .task-group .task-group-th').css({ 'left': offsetLeft + 'px' });
        angular.element('.task-track-panel .task-panel .task-panel-body .task-list .task-list-th').css({ 'left': offsetLeft + 'px' });
      });
    }

    function getTaskPlanInfo(taskId) {
      TaskTrackService.getTaskPlanInfo(taskId).then(function(taskPlanData) {
        vm.taskPlanInfo = TaskTrackService.handlePlanData(taskPlanData);
        if (taskPlanData.status == '1' || taskPlanData.status == '2' || taskPlanData.status == '4') {
          $interval(function() { refreshPartInfo($stateParams.taskId); }, intervalTime * 1000);
          if (taskPlanData.status == '2' || taskPlanData.status == '4') {
            $interval(setCurrentTime, intervalTime * 1000);
          }
        }
        if (taskPlanData.status == '2' || taskPlanData.status == '4') {
          setCurrentTime();
        }
      }, function(msg) {
        throw msg;
      });
    }

    function setCurrentTime() {
      var currentDate = new Date();
      var timeAxis = _.keys(vm.taskPlanInfo.timeAxis);
      var maxDate = new Date(parseInt(timeAxis.pop()));
      maxDate.setMinutes(59);
      maxDate.setSeconds(59);
      maxDate.setMilliseconds(999);
      var minDate = new Date(parseInt(timeAxis[0]));
      minDate.setMinutes(0);
      minDate.setSeconds(0);
      minDate.setMilliseconds(0);
      if (currentDate.getTime() > minDate.getTime() && currentDate.getTime() < maxDate.getTime()) {
        var startTime = timeAxis[0];
        currentDate.setMilliseconds(0);
        var offset = currentDate.getTime() - startTime;
        currentDate.setMinutes(0);
        currentDate.setSeconds(0);

        var min = Math.ceil(new Date().getMinutes() / 6) * 6;
        if (new Date().getMinutes() % 6 === 0) {
          if (new Date().getSeconds() > 0) { min += 6; }
        }
        vm.currentTime = {
          time: currentDate.getTime(),
          min: min,
          offset: parseInt(parseInt(offset / 1000 / 60) / mincell) * minpixel
        };

        if (vm.currentTime.offset > 350) {
          $timeout(function() {
            angular.element('.task-track-panel .task-panel .task-panel-body .task-group-list').css({ 'width': 230 * (timeAxis.length + 1) + 'px' });
            angular.element('.task-panel').scrollLeft(vm.currentTime.offset - 350);
          }, 1000);
        }
      }
    }

    function refreshPartInfo(taskId) {
      TaskTrackService.getTaskPlanInfo(taskId).then(function(taskPlanData) {
        TaskTrackService.refreshPartInfo(vm.taskPlanInfo, taskPlanData);
      }, function(msg) {
        throw msg;
      });
    }

    function showTaskDetailsModal(task, taskType) {
      angular.element('#taskDetailsModal').modal();
      vm.currentTask = task;
      vm.currentTask.taskType = taskType;
    }
  }

  function TaskTrackInfoController($stateParams, $rootScope, $scope, $interval, TaskTrackService) {
    var vm = this;

    vm.projectInfo = null;
    vm.fallbackTaskList = [];
    vm.changeList = [];
    vm.currentTask = {};
    vm.projectStatus = TaskTrackService.getProjectStatus();

    vm.translateChangeStatus = translateChangeStatus;
    vm.translateFallbackStatus = translateFallbackStatus;
    vm.translateProjectStatus = translateProjectStatus;

    vm.getCurrentChangeName = getCurrentChangeName;

    activate();

    //////////////////////////////////////

    function activate() {
      if ($stateParams.taskId) {
        getTaskPlanInfo($stateParams.taskId);
        var refreshTimer = $interval(refreshProjectInfo, 60 * 1000);
        $scope.$on('$destroy', function() {
          $interval.cancel(refreshTimer);
        })
      }
    }

    function getTaskPlanInfo(taskId) {
      TaskTrackService.getTaskPlanInfo(taskId).then(function(detail) {
        vm.projectInfo = TaskTrackService.handleDetail(detail);
        if (vm.projectInfo.status == '2') {
          getChangeList(vm.projectInfo.projectId);
        }
      }, function(msg) {
        throw msg;
      });
    }

    function refreshProjectInfo() {
      if (vm.projectInfo.status == '3' || vm.projectInfo.status == '5') {
        // project finished
        return;
      }
      TaskTrackService.getTaskPlanInfo($stateParams.taskId).then(function(detail) {
        if (detail.status == '2') {
          getChangeList(vm.projectInfo.projectId);
        }
        vm.projectInfo = TaskTrackService.refreshProjectInfo(vm.projectInfo, detail);
      }, function(msg) {
        throw msg;
      });
    }

    function getChangeList(projectId) {
      TaskTrackService.getChangeList(projectId).then(function(changeList) {
        vm.changeList = changeList;
        vm.currentTask.changeId = changeList[0].changeId;
      }, function(msg) {
        throw msg;
      });
    }

    function translateProjectStatus(task, status) {
      var data = {
        projectId: vm.projectInfo.projectId,
        status: status,
        changeId: task.changeId,
      };
      TaskTrackService.translateProjectStatus(data).then(function() {
        getTaskPlanInfo(vm.projectInfo.projectId);
        angular.element('#fallbackList').modal('hide');
        $rootScope.showMessage('操作成功', 'success', 3);
      }, function(msg) {
        angular.element('#fallbackList').modal('hide');
        $rootScope.showMessage(msg, 'danger', 3);
      })
    }

    function translateChangeStatus(task, status) {
      if (!vm.projectInfo.status == '1' || !vm.projectInfo.status == '2') {
        return;
      } else if (vm.projectInfo.status == '1' && status === 1 && vm.projectInfo.expectStartTime > new Date().getTime()) {
        $rootScope.showMessage('项目开始时间未到，不能开始任务。', 'danger', 3);
        return;
      }
      TaskTrackService.translateChangeStatus(task.changeId, status).then(function() {
        refreshProjectInfo();
        $rootScope.showMessage('操作成功', 'success', 3);
      }, function(msg) {
        $rootScope.showMessage(msg, 'danger');
      });
    }

    function translateFallbackStatus(task, status) {
      if (!vm.projectInfo.status == '4') {
        return;
      }
      TaskTrackService.translateFallbackStatus(task.fallbackId, status).then(function() {
        refreshProjectInfo();
        $rootScope.showMessage('操作成功', 'success', 3);
      }, function(msg) {
        $rootScope.showMessage(msg, 'danger');
      });
    }

    function getCurrentChangeName(changeId) {
      vm.currentTask.changeName = _.find(vm.changeList, { 'changeId': changeId }).changeName;
    }
  }

})();